package cn.tsyz.local.modules.user.repository.impl;

import cn.tsyz.local.modules.user.model.User;
import cn.tsyz.local.modules.user.repository.UserRepository;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Repository
public class UserRepositoryImpl implements UserRepository {

    private final Map<Long, User> userStorage = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);

    public UserRepositoryImpl() {
        // 初始化一些测试数据
        User admin = User.builder()
                .id(idGenerator.getAndIncrement())
                .username("admin")
                .password("123456") // 实际项目中应该加密
                .email("admin@example.com")
                .enabled(true)
                .build();
        userStorage.put(admin.getId(), admin);

        User user = User.builder()
                .id(idGenerator.getAndIncrement())
                .username("user")
                .password("123456") // 实际项目中应该加密
                .email("user@example.com")
                .enabled(true)
                .build();
        userStorage.put(user.getId(), user);
    }

    @Override
    public Optional<User> findById(Long id) {
        return Optional.ofNullable(userStorage.get(id));
    }

    @Override
    public Optional<User> findByUsername(String username) {
        return userStorage.values().stream()
                .filter(user -> user.getUsername().equals(username))
                .findFirst();
    }

    @Override
    public List<User> findAll() {
        return new ArrayList<>(userStorage.values());
    }

    @Override
    public User save(User user) {
        if (user.getId() == null) {
            user.setId(idGenerator.getAndIncrement());
        }
        userStorage.put(user.getId(), user);
        return user;
    }

    @Override
    public void deleteById(Long id) {
        userStorage.remove(id);
    }
}
